package com.wenyl.linear.stack;

import lombok.Data;

/**
 * @author Swimming Dragon
 * @description: 链表实现栈
 * @date 2024年10月17日 22:17
 */
@Data
public class LinkedStack {
    // 头元素
    private LSNode head;
    // 尾元素
    private LSNode tail;
    // 元素个数
    private int length;
    public LinkedStack(){
        head = tail = null;
        length = 0;
    }
    /**
     * 数据入栈
     * @param data 数据
     */
    public void push(int data){
        LSNode node = new LSNode(data);
        if(isEmpty()){
            head = node;
            tail = node;
            length++;
            return;
        }
        tail.setNext(node);
        node.setPre(tail);
        tail = node;
        length++;
    }

    /**
     * 栈顶元素出栈，空栈出-1
     */
    public int pop(){
        // 没有元素
        if(isEmpty()){
            System.out.println("空栈");
            return -1;
        }
        LSNode popData;
        // 只有一个元素，判断头元素即可
        if(size() == 1){
            popData = tail;
            head = tail = null;
            length--;
            return popData.getData();
        }
        popData = tail;
        tail = tail.getPre();
        tail.setNext(null);
        popData.setPre(null);
        length--;
        return popData.getData();
    }

    public void printAsPush(){
        if(isEmpty()){
            System.out.println("链表为空");
            return;
        }
        LSNode currentNode = head;
        do{
            System.out.print(currentNode.getData()+"  ");
            currentNode = currentNode.getNext();
        }while(currentNode != null);
        System.out.println();
    }
    public void printAsPop(){
        if(isEmpty()){
            System.out.println("链表为空");
            return;
        }
        LSNode currentNode = tail;
        do{
            System.out.print(currentNode.getData()+"  ");
            currentNode = currentNode.getPre();
        }while(currentNode != null);
        System.out.println();
    }
    /**
     * @return 返回链表当前元素个数
     */
    public int size(){
        return length;
    }

    /**
     * @return 链表为空返回true，否则返回false
     */
    public boolean isEmpty(){
        return size() == 0;
    }
}

@Data
class LSNode{
    private int data;
    private LSNode next;
    private LSNode pre;
    public LSNode(int data){
        this.data = data;
        this.next = null;
        this.pre = null;
    }
}
